<?php

namespace App\Basic;

use DateInterval;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Database\Eloquent\Model as BaseModel;

class Model extends BaseModel
{
    /**
     * @var bool
     */
    public $timestamps = false;

    /**
     * @param int|string $value
     * @param string $key
     * @param int|DateInterval|null $ttl
     * @return static|Builder|null
     */
    public static function findFromCache(int|string $value, string $key = 'id', null|int|DateInterval $ttl = null): static|Builder|null
    {
        $static = new static();
        $driver = Cache::driver('redis');
        $name = sprintf("%s:%s:%s:%s", $static->getConnectionName(), $static->getTable(), $key, $value);
        $cacheData = $driver->get($name);
        if ($cacheData) {
            $data  = unserialize($cacheData);
        } else {
            $data = $static->newQuery()->firstWhere($key, $value);
            $driver->set($name, serialize($data), $ttl);
        }
        return $data;
    }
}
